import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // state
  const userInfo = ref(null)
  const token = ref(localStorage.getItem('token') || '')

  // getters
  const isLogin = computed(() => !!token.value)

  // actions
  const setUserInfo = (info) => {
    userInfo.value = info
  }

  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  const clearUserInfo = () => {
    userInfo.value = null
    token.value = ''
    localStorage.removeItem('token')
  }

  const logout = () => {
    clearUserInfo()
  }

  return {
    // state
    userInfo,
    token,
    
    // getters
    isLogin,
    
    // actions
    setUserInfo,
    setToken,
    clearUserInfo,
    logout
  }
})